package com.github.iot.activity;

import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.github.iot.R;
import com.github.iot.adapter.UserRecycleAdapter;
import com.github.iot.dao.CommonDaoUtils;
import com.github.iot.dao.DaoUtilsStore;
import com.github.iot.entity.User;
import com.github.iot.utils.ActivityUtils;
import com.github.iot.utils.BarUtils;
import com.github.iot.view.RxTitle;

import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * 用户列表Activity
 *
 * @Author: 梁声洪
 * @Date: 2019/12/09 9:14
 * @Version: v1.0.0
 */
public class UserListActivity extends AppCompatActivity {

    @BindView(R.id.rx_title)
    RxTitle mTitle;

    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BarUtils.setStatusBarColor(this, R.color.colorPrimaryDark);
        setContentView(R.layout.activity_user_list);

        ButterKnife.bind(this);

        initView();
        initData();
    }

    private void initView() {
        mTitle.setLeftFinish(this);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    private void initData() {
        Observable.timer(100, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(t -> getData());
    }

    private void getData() {
        CommonDaoUtils<User> commonDao = DaoUtilsStore.getInstance().getUserDaoUtils();
        String sql = "order by type asc";
        List<User> list = commonDao.queryByNativeSql(sql, null);

        UserRecycleAdapter adapter = new UserRecycleAdapter(UserListActivity.this, list);
        mRecyclerView.setAdapter(adapter);
    }

    @OnClick({R.id.fab})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.fab) {
            ActivityUtils.skipActivity(UserListActivity.this, AddUserActivity.class);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

}